﻿using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Mechanical; // 需要 Space, Zone, HVACLoadSpaceType, SpaceType, ConditionType, OccupancyUnit 等枚举
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Diagnostics;
using System.Globalization; // CultureInfo

namespace RevitProject.SpaceManager.ViewModel.SpaceViewModel
{
    public partial class SpaceDisplayViewModel : ObservableObject
    {
        private readonly Space _space;
        private readonly Document _doc; // 添加 _doc 字段



        public Space RevitSpace => _space;

        // --- 核心属性 ---
        /// <summary>空间所在的楼层名称。</summary>
        public string LevelName { get; private set; }
        /// <summary>空间所在楼层的标高 (毫米，整数)。</summary>
        public string LevelElevation { get; private set; }
        /// <summary>空间名称。</summary>
        public string SpaceName { get; private set; }
        /// <summary>空间编号。</summary>
        public string SpaceNumber { get; private set; }
        /// <summary>格式化后的空间面积 (平方米，保留两位小数)。</summary>
        public string FormattedArea { get; private set; }
        /// <summary>空间的 HVAC 空间类型名称。</summary>
        private string _spaceTypeName;
        public string SpaceTypeName
        {
            get => _spaceTypeName;
            set => SetProperty(ref _spaceTypeName, value); // <-- 现在是 public set
        }
        // --- 几何与位置 ---
        /// <summary>格式化后的空间体积 (立方米，保留两位小数)。</summary>
        public string FormattedVolume { get; private set; }
        /// <summary>格式化后的空间周长 (米，保留两位小数)。</summary>
        public string FormattedPerimeter { get; private set; }
        /// <summary>空间底部相对于其标高的偏移量 (毫米，整数)。</summary>
        public string FormattedBaseOffset { get; private set; }
        /// <summary>空间顶部相对于其标高的偏移量 (毫米，整数)。</summary>
        public string FormattedLimitOffset { get; private set; }

        // --- 分区与关联 ---
        /// <summary>空间所属的分区 (Zone) 名称。</summary>
        public string ZoneName { get; private set; }
        /// <summary>通过 Space.Room 属性获取的关联房间的名称。</summary>
        public string RoomNameFromSpace { get; private set; }
        /// <summary>通过 Space.Room 属性获取的关联房间的编号。</summary>
        public string RoomNumberFromSpace { get; private set; }

        // --- HVAC 计算值 ---
        /// <summary>格式化后的计算出的送风量 (升/秒，保留一位小数)。</summary>
        public string FormattedCalculatedSupplyAirflow { get; private set; }
        /// <summary>格式化后的计算出的冷负荷 (瓦特，整数)。</summary>
        public string FormattedCalculatedCoolingLoad { get; private set; }
        /// <summary>格式化后的计算出的热负荷 (瓦特，整数)。</summary>
        public string FormattedCalculatedHeatingLoad { get; private set; }

        // --- HVAC 实际/测量值 ---
        /// <summary>格式化后的实际送风量 (升/秒，保留一位小数)。</summary>
        public string FormattedActualSupplyAirflow { get; private set; }
        /// <summary>格式化后的实际回风量 (升/秒，保留一位小数)。</summary>
        public string FormattedActualReturnAirflow { get; private set; }
        /// <summary>格式化后的实际排风量 (升/秒，保留一位小数)。</summary>
        public string FormattedActualExhaustAirflow { get; private set; }
        /// <summary>格式化后的实际照明负荷 (瓦特，整数)。</summary>
        public string FormattedActualLightingLoad { get; private set; }
        /// <summary>格式化后的实际设备负荷 (瓦特，整数)。</summary>
        public string FormattedActualPowerLoad { get; private set; }
        /// <summary>格式化后的实际其他负荷 (瓦特，整数)。</summary>
        public string FormattedActualOtherLoad { get; private set; }
        /// <summary>格式化后的实际 HVAC 负荷 (瓦特，整数)。</summary>
        public string FormattedActualHVACLoad { get; private set; }

        // --- HVAC 设计/指定值 (可能来自空间或空间类型) ---
        /// <summary>格式化后的设计送风量 (升/秒，保留一位小数)。</summary>
        public string FormattedDesignSupplyAirflow { get; private set; }
        /// <summary>格式化后的设计回风量 (升/秒，保留一位小数)。</summary>
        public string FormattedDesignReturnAirflow { get; private set; }
        /// <summary>格式化后的设计排风量 (升/秒，保留一位小数)。</summary>
        public string FormattedDesignExhaustAirflow { get; private set; }
        /// <summary>格式化后的设计冷负荷 (瓦特，整数)。</summary>
        public string FormattedDesignCoolingLoad { get; private set; }
        /// <summary>格式化后的设计热负荷 (瓦特，整数)。</summary>
        public string FormattedDesignHeatingLoad { get; private set; }
        /// <summary>格式化后的设计照明负荷 (瓦特，整数)。</summary>
        public string FormattedDesignLightingLoad { get; private set; }
        /// <summary>格式化后的设计设备负荷 (瓦特，整数)。</summary>
        public string FormattedDesignPowerLoad { get; private set; }
        /// <summary>格式化后的设计 HVAC 负荷密度 (瓦特/平方米，保留两位小数)。</summary>
        public string FormattedDesignHVACLoadPerArea { get; private set; }
        /// <summary>格式化后的设计其他负荷密度 (瓦特/平方米，保留两位小数)。</summary>
        public string FormattedDesignOtherLoadPerArea { get; private set; }

        // --- 人员和占用 ---
        /// <summary>占用率计算方式 (如 AreaPerPerson, NumberOfPeople)。</summary>
        public string OccupancyUnit { get; private set; }
        /// <summary>空间中的人数。</summary>
        public int NumberOfPeople { get; private set; }
        /// <summary>格式化后的人均面积 (平方米，保留两位小数)。</summary>
        public string FormattedAreaPerPerson { get; private set; }
        /// <summary>格式化后的人员潜热增益 (瓦特/人，保留一位小数)。</summary>
        public string FormattedLatentHeatGainPerPerson { get; private set; }
        /// <summary>格式化后的人员显热增益 (瓦特/人，保留一位小数)。</summary>
        public string FormattedSensibleHeatGainPerPerson { get; private set; }
        /// <summary>指示空间是否可占用 ("是" 或 "否")。</summary>
        public string IsOccupiableDisplay { get; private set; }

        // --- 新风 ---
        /// <summary>格式化后的新风量 (升/秒，保留一位小数)。</summary>
        public string FormattedOutdoorAirflow { get; private set; }
        /// <summary>新风计算标准 (如 ByPeopleAndByArea, ByACH 等)。</summary>
        public string OutdoorAirFlowStandardDisplay { get; private set; }
        /// <summary>格式化后的每面积新风量 (升/秒/平方米，保留两位小数)。</summary>
        public string FormattedOutdoorAirPerArea { get; private set; }
        /// <summary>格式化后的每人新风量 (升/秒，保留一位小数)。</summary>
        public string FormattedOutdoorAirPerPerson { get; private set; }
        /// <summary>格式化后的每小时换气次数 (保留两位小数)。</summary>
        public string FormattedAirChangesPerHour { get; private set; }

        // --- 照明与反射 ---
        /// <summary>格式化后的天花板反射率 (%)。</summary>
        public string FormattedCeilingReflectance { get; private set; }
        /// <summary>格式化后的地板反射率 (%)。</summary>
        public string FormattedFloorReflectance { get; private set; }
        /// <summary>格式化后的墙面反射率 (%)。</summary>
        public string FormattedWallReflectance { get; private set; }
        /// <summary>格式化后的照明计算工作平面高度 (毫米，整数)。</summary>
        public string FormattedLightingCalculationWorkplane { get; private set; }
        /// <summary>照明负荷单位 (如 WattsPerSquareFoot, WattsPerSquareMeter)。</summary>
        public string LightingLoadUnitDisplay { get; private set; }
        /// <summary>设备负荷单位 (如 WattsPerSquareFoot, WattsPerSquareMeter)。</summary>
        public string PowerLoadUnitDisplay { get; private set; }

        // --- 状态与类型 ---
        /// <summary>空间条件类型 (如 HeatedAndCooled, Unconditioned)。</summary>
        public string ConditionTypeDisplay { get; private set; }
        /// <summary>指示空间是否为静压送风腔 ("是" 或 "否")。</summary>
        public string IsPlenumDisplay { get; private set; }

        // --- 标识与阶段 ---
        /// <summary>空间的唯一标识符 (UniqueId)。</summary>
        public string UniqueId { get; private set; }
        /// <summary>空间创建时所属的阶段名称。</summary>
        public string PhaseCreatedName { get; private set; }
        /// <summary>空间拆除时所属的阶段名称 ("无" 表示未拆除)。</summary>
        public string PhaseDemolishedName { get; private set; }

        // --- UI 选中状态 ---
        private bool _isSelected;
        /// <summary>指示该空间在 DataGrid 中是否被选中。</summary>
        public bool IsSelected { get => _isSelected; set => SetProperty(ref _isSelected, value); }


        // 构造函数 (添加所有属性的获取和格式化)
        public SpaceDisplayViewModel(Space space, Document doc)
        {
            if (space == null || !space.IsValidObject) throw new ArgumentNullException(nameof(space));
            if (doc == null || !doc.IsValidObject) throw new ArgumentNullException(nameof(doc));
            _space = space;
            _doc = doc; // 保存 Document 引用

            // --- 基本信息 ---
            // 调用 GetFormattedValue<string>
            LevelName = GetFormattedValue<string>(() => _space.Level?.Name, "未知楼层");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...)
            LevelElevation = GetFormattedValue(() => _space.Level?.Elevation, UnitTypeId.Millimeters, "F0", "---");
            // 调用 GetFormattedValue<string>
            SpaceName = GetFormattedValue<string>(() => _space.Name, "无名称");
            // 调用 GetFormattedValue<string>
            SpaceNumber = GetFormattedValue<string>(() => _space.Number, "无编号");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedArea = GetFormattedValue(() => _space.Area as double?, UnitTypeId.SquareMeters, "N2", "---");
            // 调用 GetFormattedValue<string>
            SpaceTypeName = GetFormattedValue<string>(() => (_doc.GetElement(_space.SpaceTypeId) as HVACLoadSpaceType)?.Name, "未指定类型");

            // --- 几何与位置 ---
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedVolume = GetFormattedValue(() => _space.Volume as double?, UnitTypeId.CubicMeters, "N2", "---");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedPerimeter = GetFormattedValue(() => _space.Perimeter as double?, UnitTypeId.Meters, "N2", "0.00");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedBaseOffset = GetFormattedValue(() => _space.BaseOffset as double?, UnitTypeId.Millimeters, "F0", "0");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedLimitOffset = GetFormattedValue(() => _space.LimitOffset as double?, UnitTypeId.Millimeters, "F0", "0");

            // --- 分区与关联 ---
            // 调用 GetFormattedValue<string>
            ZoneName = GetFormattedValue<string>(() => _space.Zone?.Name, "无分区");
            // 调用 GetFormattedValue<string>
            RoomNameFromSpace = GetFormattedValue<string>(() => _space.Room?.Name, "无");
            // 调用 GetFormattedValue<string>
            RoomNumberFromSpace = GetFormattedValue<string>(() => _space.Room?.Number, "无");

            // --- 人员和占用 ---
            // 调用 GetFormattedValue<string>
            OccupancyUnit = GetFormattedValue<string>(() => _space.OccupancyUnit.ToString(), "---");
            // 调用 GetFormattedValue<int>
            NumberOfPeople = GetFormattedValue(() => Convert.ToInt32(_space.NumberofPeople), 0); // Lambda 返回 int
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedAreaPerPerson = GetFormattedValue(() => _space.AreaperPerson as double?, UnitTypeId.SquareMeters, "N2", "0.00");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedLatentHeatGainPerPerson = GetFormattedValue(() => _space.LatentHeatGainperPerson as double?, UnitTypeId.Watts, "F1", "0.0");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedSensibleHeatGainPerPerson = GetFormattedValue(() => _space.SensibleHeatGainperPerson as double?, UnitTypeId.Watts, "F1", "0.0");
            // 调用 GetFormattedValue<string>
            IsOccupiableDisplay = GetFormattedValue(() => _space.Occupiable ? "是" : "否", "否");

            // --- 照明与反射 ---
            // 调用 GetFormattedValue(Func<double?>, string, ...) - 需要将 double 转 double?
            FormattedCeilingReflectance = GetFormattedValue(() => _space.CeilingReflectance * 100 as double?, "F0", "0") + "%";
            FormattedFloorReflectance = GetFormattedValue(() => _space.FloorReflectance * 100 as double?, "F0", "0") + "%";
            FormattedWallReflectance = GetFormattedValue(() => _space.WallReflectance * 100 as double?, "F0", "0") + "%";
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedLightingCalculationWorkplane = GetFormattedValue(() => _space.LightingCalculationWorkplane as double?, UnitTypeId.Millimeters, "F0", "0");
            // 调用 GetFormattedValue<string>
            LightingLoadUnitDisplay = GetFormattedValue<string>(() => _space.LightingLoadUnit.ToString(), "---");
            PowerLoadUnitDisplay = GetFormattedValue<string>(() => _space.PowerLoadUnit.ToString(), "---");

            // --- 状态与类型 ---
            // 调用 GetFormattedValue<string>
            ConditionTypeDisplay = GetFormattedValue<string>(() => _space.ConditionType.ToString(), "---");
            // 调用 GetFormattedValue<string>
            IsPlenumDisplay = GetFormattedValue(() => _space.Plenum ? "是" : "否", "否");

            // --- 标识与阶段 ---
            // 调用 GetFormattedValue<string>
            UniqueId = GetFormattedValue<string>(() => _space.UniqueId, "");
            // 调用 GetFormattedValue<string>
            PhaseCreatedName = GetFormattedValue<string>(() => (_doc.GetElement(_space.CreatedPhaseId) as Phase)?.Name, "未知");
            PhaseDemolishedName = GetFormattedValue<string>(() => _space.DemolishedPhaseId != ElementId.InvalidElementId ? (_doc.GetElement(_space.DemolishedPhaseId) as Phase)?.Name : "无", "无");

            // ---  处理可能未计算的属性 (保留 try-catch)  ---
            string defaultNotComputed = "未计算";
            string defaultNotSet = "未设置";

            // 计算值
            try { FormattedCalculatedSupplyAirflow = GetFormattedValue(() => _space.CalculatedSupplyAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedCalculatedSupplyAirflow = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: CalculatedSupplyAirflow not computed."); }
            catch (Exception ex) { FormattedCalculatedSupplyAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting CalculatedSupplyAirflow: {ex.Message}"); }

            try { FormattedCalculatedCoolingLoad = GetFormattedValue(() => _space.CalculatedCoolingLoad as double?, UnitTypeId.Watts, "F0", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedCalculatedCoolingLoad = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: CalculatedCoolingLoad not computed."); }
            catch (Exception ex) { FormattedCalculatedCoolingLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting CalculatedCoolingLoad: {ex.Message}"); }

            try { FormattedCalculatedHeatingLoad = GetFormattedValue(() => _space.CalculatedHeatingLoad as double?, UnitTypeId.Watts, "F0", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedCalculatedHeatingLoad = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: CalculatedHeatingLoad not computed."); }
            catch (Exception ex) { FormattedCalculatedHeatingLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting CalculatedHeatingLoad: {ex.Message}"); }

            // 实际值
            try { FormattedActualSupplyAirflow = GetFormattedValue(() => _space.ActualSupplyAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualSupplyAirflow = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualSupplyAirflow not computed."); }
            catch (Exception ex) { FormattedActualSupplyAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualSupplyAirflow: {ex.Message}"); }

            try { FormattedActualReturnAirflow = GetFormattedValue(() => _space.ActualReturnAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualReturnAirflow = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualReturnAirflow not computed."); }
            catch (Exception ex) { FormattedActualReturnAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualReturnAirflow: {ex.Message}"); }

            try { FormattedActualExhaustAirflow = GetFormattedValue(() => _space.ActualExhaustAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualExhaustAirflow = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualExhaustAirflow not computed."); }
            catch (Exception ex) { FormattedActualExhaustAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualExhaustAirflow: {ex.Message}"); }

            try { FormattedActualLightingLoad = GetFormattedValue(() => _space.ActualLightingLoad as double?, UnitTypeId.Watts, "F0", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualLightingLoad = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualLightingLoad not computed."); }
            catch (Exception ex) { FormattedActualLightingLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualLightingLoad: {ex.Message}"); }

            try { FormattedActualPowerLoad = GetFormattedValue(() => _space.ActualPowerLoad as double?, UnitTypeId.Watts, "F0", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualPowerLoad = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualPowerLoad not computed."); }
            catch (Exception ex) { FormattedActualPowerLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualPowerLoad: {ex.Message}"); }

            try { FormattedActualOtherLoad = GetFormattedValue(() => _space.ActualOtherLoad as double?, UnitTypeId.Watts, "F0", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualOtherLoad = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualOtherLoad not computed."); }
            catch (Exception ex) { FormattedActualOtherLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualOtherLoad: {ex.Message}"); }

            try { FormattedActualHVACLoad = GetFormattedValue(() => _space.ActualHVACLoad as double?, UnitTypeId.Watts, "F0", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedActualHVACLoad = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: ActualHVACLoad not computed."); }
            catch (Exception ex) { FormattedActualHVACLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting ActualHVACLoad: {ex.Message}"); }

            // 设计值
            try { FormattedDesignSupplyAirflow = GetFormattedValue(() => _space.DesignSupplyAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotSet); }
            catch (Exception ex) { FormattedDesignSupplyAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignSupplyAirflow: {ex.Message}"); }

            try { FormattedDesignReturnAirflow = GetFormattedValue(() => _space.DesignReturnAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotSet); }
            catch (Exception ex) { FormattedDesignReturnAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignReturnAirflow: {ex.Message}"); }

            try { FormattedDesignExhaustAirflow = GetFormattedValue(() => _space.DesignExhaustAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotSet); }
            catch (Exception ex) { FormattedDesignExhaustAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignExhaustAirflow: {ex.Message}"); }

            try { FormattedDesignCoolingLoad = GetFormattedValue(() => _space.DesignCoolingLoad as double?, UnitTypeId.Watts, "F0", defaultNotSet); }
            catch (Exception ex) { FormattedDesignCoolingLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignCoolingLoad: {ex.Message}"); }

            try { FormattedDesignHeatingLoad = GetFormattedValue(() => _space.DesignHeatingLoad as double?, UnitTypeId.Watts, "F0", defaultNotSet); }
            catch (Exception ex) { FormattedDesignHeatingLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignHeatingLoad: {ex.Message}"); }

            try { FormattedDesignLightingLoad = GetFormattedValue(() => _space.DesignLightingLoad as double?, UnitTypeId.Watts, "F0", defaultNotSet); }
            catch (Exception ex) { FormattedDesignLightingLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignLightingLoad: {ex.Message}"); }

            try { FormattedDesignPowerLoad = GetFormattedValue(() => _space.DesignPowerLoad as double?, UnitTypeId.Watts, "F0", defaultNotSet); }
            catch (Exception ex) { FormattedDesignPowerLoad = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignPowerLoad: {ex.Message}"); }

            try { FormattedDesignHVACLoadPerArea = GetFormattedValue(() => _space.DesignHVACLoadperArea as double?, UnitTypeId.WattsPerSquareMeter, "F2", defaultNotSet); }
            catch (Exception ex) { FormattedDesignHVACLoadPerArea = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignHVACLoadperArea: {ex.Message}"); }

            try { FormattedDesignOtherLoadPerArea = GetFormattedValue(() => _space.DesignOtherLoadperArea as double?, UnitTypeId.WattsPerSquareMeter, "F2", defaultNotSet); }
            catch (Exception ex) { FormattedDesignOtherLoadPerArea = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting DesignOtherLoadperArea: {ex.Message}"); }

            // 新风
            try { FormattedOutdoorAirflow = GetFormattedValue(() => _space.OutdoorAirflow as double?, UnitTypeId.LitersPerSecond, "F1", defaultNotComputed); }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException) { FormattedOutdoorAirflow = defaultNotComputed; Debug.WriteLine($"Space {_space.Id}: OutdoorAirflow not computed."); }
            catch (Exception ex) { FormattedOutdoorAirflow = "错误"; Debug.WriteLine($"Space {_space.Id}: Error getting OutdoorAirflow: {ex.Message}"); }

            // 调用 GetFormattedValue<string>
            OutdoorAirFlowStandardDisplay = GetFormattedValue<string>(() => _space.OutdoorAirFlowStandard.ToString(), "---");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedOutdoorAirPerArea = GetFormattedValue(() => _space.OutdoorAirPerArea as double?, UnitTypeId.LitersPerSecondSquareMeter, "F2", "0.00");
            // 调用 GetFormattedValue(Func<double?>, ForgeTypeId, ...) - 需要将 double 转 double?
            FormattedOutdoorAirPerPerson = GetFormattedValue(() => _space.OutdoorAirPerPerson as double?, UnitTypeId.LitersPerSecond, "F1", "0.0"); // 再次确认单位
            // 调用 GetFormattedValue(Func<double?>, string, ...) - 需要将 double 转 double?
            FormattedAirChangesPerHour = GetFormattedValue(() => _space.AirChangesPerHour as double?, "F2", "0.00");


            // --- 初始化选中状态 ---
            IsSelected = false;
        }

        // --- 辅助方法 ---

        // 获取基本类型值
        // 重载 1: 处理非数值类型 或 不需要单位转换/特定格式的数值 (如 int)
        private T GetFormattedValue<T>(Func<T> valueGetter, T defaultValue)
        {
            try
            {
                // 对于 int 类型，如果源是 double，进行显式转换
                if (typeof(T) == typeof(int) && valueGetter() is double doubleValue)
                {
                    return (T)(object)Convert.ToInt32(doubleValue); // 先转 object 再转 T
                }
                return valueGetter() ?? defaultValue;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error getting value for type {typeof(T)}: {ex.Message}");
                return defaultValue;
            }
        }

        // 重载 2: 处理需要单位转换和格式化的 double? 类型
        private string GetFormattedValue(Func<double?> valueGetter, ForgeTypeId displayUnitTypeId, string format, string defaultValue, double zeroThreshold = 1e-9)
        {
            try
            {
                double? internalValueNullable = valueGetter(); // 获取 double?

                // 如果值为 null，直接返回默认值
                if (!internalValueNullable.HasValue)
                {
                    return defaultValue;
                }

                double internalValue = internalValueNullable.Value; // 获取实际的 double 值

                // --- 后续逻辑与之前的 GetFormattedValue(Func<double>...) 相同 ---
                if (displayUnitTypeId != null && !string.IsNullOrEmpty(displayUnitTypeId.TypeId))
                {
                    double displayValue = UnitUtils.ConvertFromInternalUnits(internalValue, displayUnitTypeId);
                    if (Math.Abs(displayValue) < zeroThreshold)
                    {
                        return 0.0.ToString(format, CultureInfo.InvariantCulture);
                    }
                    return displayValue.ToString(format, CultureInfo.InvariantCulture);
                }
                else
                {
                    if (Math.Abs(internalValue) < zeroThreshold)
                    {
                        return 0.0.ToString(format, CultureInfo.InvariantCulture);
                    }
                    return internalValue.ToString(format, CultureInfo.InvariantCulture);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error getting/formatting nullable double value: {ex.Message}");
                return defaultValue;
            }
        }

        // 重载 3: 处理不需要单位转换，但需要特定格式的 double? 类型 (例如反射率)
        private string GetFormattedValue(Func<double?> valueGetter, string format, string defaultValue, double zeroThreshold = 1e-9)
        {
            // 调用重载 2，将 displayUnitTypeId 设为 null
            return GetFormattedValue(valueGetter, null, format, defaultValue, zeroThreshold);
        }


        // 获取需要单位转换和格式化的数值
        private string GetFormattedValue(Func<double> valueGetter, ForgeTypeId displayUnitTypeId, string format, string defaultValue, double zeroThreshold = 1e-9)
        {
            try
            {
                double internalValue = valueGetter();
                if (displayUnitTypeId != null && !string.IsNullOrEmpty(displayUnitTypeId.TypeId))
                {
                    double displayValue = UnitUtils.ConvertFromInternalUnits(internalValue, displayUnitTypeId);
                    // 检查是否接近零
                    if (Math.Abs(displayValue) < zeroThreshold)
                    {
                        // 根据格式返回 0
                        return 0.0.ToString(format, CultureInfo.InvariantCulture);
                    }
                    return displayValue.ToString(format, CultureInfo.InvariantCulture);
                }
                else // 不需要单位转换，直接格式化
                {
                    // 检查是否接近零
                    if (Math.Abs(internalValue) < zeroThreshold)
                    {
                        return 0.0.ToString(format, CultureInfo.InvariantCulture);
                    }
                    return internalValue.ToString(format, CultureInfo.InvariantCulture);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error getting/formatting numeric value: {ex.Message}");
                return defaultValue;
            }
        }
    }
}